package Classic150;

public class 岛屿数量 {
    char[][] grid;
    int[][] next = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

    /*
        dfs基础，注意边界条件
     */
    public int numIslands(char[][] grid) {
        int res = 0;
        this.grid = grid;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    res++;
                    dfs(i, j);
                }
            }
        }
        return res;
    }

    private void dfs(int r, int c) {
        if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == '0') {
            return;
        }
        grid[r][c] = '0';
        for (int i = 0; i < 4; i++) {
            dfs(r + next[i][0], c + next[i][1]);
        }
    }
}
